<template>
  <div>
    <div class="wrapper">
      <div class="crud-opts">
        <span class="crud-opts-left">
          <el-button size="mini" type="primary" icon="el-icon-plus">
            新用户
          </el-button>
          <!-- <el-button size="mini" type="success" icon="el-icon-edit">
            修改
          </el-button>
          <el-button
            slot="reference"
            type="danger"
            icon="el-icon-delete"
            size="mini"
          >
            删除
          </el-button>
          <el-button size="mini" type="warning" icon="el-icon-download"
            >导出</el-button
          > -->
        </span>
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
      >
        <el-table-column prop="id" label="编号"> </el-table-column>
        <el-table-column prop="nickName" label="昵称"> </el-table-column>
        <el-table-column prop="avatar" label="头像">
          <template slot-scope="scope">
            <el-image
              class="user-avatar"
              lazy
              :src="spliceUrl(scope.row.avatar) + '?imageView2/1/w/80/h/80'"
              :preview-src-list="[spliceUrl(scope.row.avatar)]"
              alt=""
            />
          </template>
        </el-table-column>
        <!-- <el-table-column prop="roleName" label="权限"></el-table-column> -->
        <el-table-column prop="phone" label="电话"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button @click="handleClick(scope.row)" type="text" size="small"
              >编辑</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-size="pageSize"
          layout="total, prev, pager, next, jumper"
          :total="total"
          hide-on-single-page
        >
        </el-pagination>
      </div>
    </div>
    <el-dialog :visible.sync="dialogVisible" title="修改用户信息">
      <el-form
        ref="form"
        v-loading="outLoad"
        :model="userlis"
        :rules="rules"
        label-width="80px"
        label-position="left"
      >
        <el-form-item label="账号" prop="username">
          <el-input
            v-model="userlis.username"
            placeholder=""
            :disabled="true"
          />
        </el-form-item>
        <el-form-item label="昵称" prop="nickName">
          <el-input v-model="userlis.nickName" placeholder="" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="userlis.phone" placeholder="" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userlis.email" placeholder="" :disabled="true" />
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="userlis.gender" style="width: 178px">
            <el-radio label="1">男</el-radio>
            <el-radio label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="权限" prop="permissions">
          <el-select
            :disabled="bool"
            v-model="permissions"
            filterable
            placeholder="请选择"
            @change="change"
          >
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
              :disabled="item.disabled === 1 ? false : true"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div style="text-align: right">
        <el-button
          type="danger"
          @click="
            () => {
              dialogVisible = false;
              outLoad = true;
            }
          "
        >
          {{ $t("permission.cancel") }}
        </el-button>
        <el-button type="primary" @click="confirmRole">
          {{ $t("permission.confirm") }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapState, mapMutations, mapActions, mapGetters } from "vuex";
import { validPhone, validEmail } from "@/utils/validate";
export default {
  name: "userList",
  data() {
    // 自定义验证
    const isvalidPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入电话号码"));
      } else if (!validPhone(value)) {
        callback(new Error("请输入正确的11位手机号码"));
      } else {
        callback();
      }
    };
    const isvalidEmail = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入邮箱"));
      } else if (!validEmail(value)) {
        callback(new Error("请输入正确格式的邮箱"));
      } else {
        callback();
      }
    };
    return {
      rules: {
        nickName: [
          { required: true, message: "请输入用户昵称", trigger: "blur" },
          { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" }
        ],
        phone: [{ required: true, trigger: "blur", validator: isvalidPhone }],
        email: [{ required: true, trigger: "blur", validator: isvalidEmail }]
      },
      loading: true, // 加载圈开启
      page: 1, // 第几页
      pageSize: 2, // 每页几条
      total: 0, // 总条数
      tableData: [], // 用户数组
      dialogVisible: false, // 编辑弹出框
      userlis: {}, // 编辑单条用户信息
      rolesList: [], // 权限列表
      permissions: "", // 当前编辑用户的权限
      bool: false, // 权限可否编辑
      outLoad: true
    };
  },
  created() {
    this.getUserLists();
  },
  methods: {
    ...mapActions("user", ["getUserList", "updateUser"]),
    ...mapActions("role", ["getRole", "getRoleList"]),

    // 用户列表
    getUserLists() {
      this.getUserList({ page: this.page, pageSize: this.pageSize }).then(
        res => {
          // console.log(res);
          this.tableData = res.data.userList;
          this.total = res.data.total;
          this.loading = false; // 关闭加载圈
        }
      );
    },

    // 切换分页
    handleCurrentChange(val) {
      this.page = val;
      this.getUserLists();
    },

    // 打开编辑框
    handleClick(row) {
      this.userlis = row; // 赋值当前编辑用户信息
      this.getRoles(row.roleId); // 获取当前用户的权限
      this.dialogVisible = true; // 打开编辑框
    },

    // 权限id获取用户权限
    getRoles(id) {
      this.getRole({ roleId: id }).then(res => {
        if (res.data.role.id === 0) {
          this.bool = true;
          this.permissions = res.data.role.roleName;
          this.loading = false;
          this.outLoad = false;
        } else {
          this.bool = false;
          this.permissions = res.data.role.roleName;
          this.getRolesList();
        }
      });
    },
    // 获取权限列表
    getRolesList() {
      let rolesListTemp = [];
      this.getRoleList().then(res => {
        rolesListTemp = res.data.rolesList;
        rolesListTemp.forEach(item => {
          var that = this;
          if (item.disabled === 0) {
            item.roleName = item.roleName + "（已关闭）";
            if (item.id == that.userlis.roleId) {
              that.permissions = item.roleName;
            }
          }
        });
        this.rolesList = rolesListTemp;
        this.outLoad = false;
      });
    },

    // 选择权限
    change(e) {
      // console.log(e);
      this.userlis.roleId = e;
    },

    confirmRole() {
      console.log(this.userlis);
      this.updateUser(this.userlis).then(res => {
        // console.log(res);
        if (res.code === 200) {
          this.$message({
            message: res.msg,
            type: "success"
          });
          this.dialogVisible = false; // 关闭编辑框
        }
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.wrapper {
  padding: 10px;
  .crud-opts {
    padding: 10px 0;
    display: -webkit-flex;
    display: flex;
    align-items: center;
  }
  .pagination {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    margin: 20px 0 0 0;
  }
  .user-avatar {
    width: 50px;
    height: 50px;
    border-radius: 10px;
  }
}
</style>
